package com.skywolf.chem.usercenter.service.impl;

import com.skywolf.chem.common.enums.ResponseCodeEnum;
import com.skywolf.chem.common.sysconfig.exception.BizException;
import com.skywolf.chem.common.sysconfig.utils.JWTUtils;
import com.skywolf.chem.common.sysconfig.utils.PasswordGenerator;
import com.skywolf.chem.usercenter.entity.User;
import com.skywolf.chem.usercenter.pojo.param.LoginParam;
import com.skywolf.chem.usercenter.service.IAuthenticationService;
import com.skywolf.chem.usercenter.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

/**
 * @ClassName AuthenticationServiceImpl.java
 * @Author Leo
 * @Version 1.0.0
 * @Description 身份认证
 * @CreateTime 2019年11月30日 21:50:00
 */
@Slf4j
@Service
public class AuthenticationServiceImpl implements IAuthenticationService {

    @Autowired
    private IUserService userService;

    @Override
    public String login(LoginParam loginParam) {
        User user = userService.getByUsername(loginParam.getUsername());
        if (user == null) {
            throw new BizException(ResponseCodeEnum.USER_INVALID_USERNAME_PASSWORD);
        }
        //验证密码是否正确
        String password = decodePassword(loginParam.getPassword());
        if (!PasswordGenerator.vatify(password, user.getPassword(), user.getSalt())) {
            throw new BizException(ResponseCodeEnum.USER_INVALID_USERNAME_PASSWORD);
        }
        //生成token
        String token = JWTUtils.sign(user.getUsername(), password);
        log.info("登录成功.token is {}", token);
        return token;
    }

    private String decodePassword(String passwordBase64) {
        String password = new String(Base64Utils.decodeFromString(passwordBase64));
        return password.substring(2);
    }
}
